<?php
/**
 *
 * @package avp
 * @version $Id: $
 * @copyright (c) 2008 Rost & Existenz
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 */

if (!defined("IN_SCRIPT")) {
    die();
}
class dbWrapper {
    var $db_link = 0;
    var $db_user;
    var $db_password;
    var $db_host;
    var $prefix;

    var $database;

    var $qCount = 0;

    function dbWrapper($user, $pass, $host, $database, $prefix)
    {
        $this->db_user = $user;
        $this->db_password = $pass;
        $this->db_host = $host;
        $this->database = $database;
        $this->prefix = $prefix;
    }

    function query($sql)
    {
        if ($this->db_link == 0) {
            $this->connect();
        }
        if ($qresult = mysql_query($sql, $this->db_link)) {
            $this->qCount++;
            return $qresult;
        } else {
	    $this->report_error('dbWrapper->query()', 'Query Failed', $sql);
        }
    }

    function query_first($sql)
    {
        if ($qresult = $this->query($sql)) {
            if (!$return = $this->fetch($qresult)) {
                return false;
            }
            $this->free_result($qresult);
            return $return ;
        } else {
            return false;
        }
    }

    function fetch($id)
    {
        return mysql_fetch_assoc($id);
    }

    function free_result($id)
    {
        mysql_free_result($id);
    }

    function get_table($name)
    {
        return $this->prefix . $name;
    }

    function get_insert_id()
    {
        return mysql_insert_id($this->db_link);
    }

    function get_num_rows($result)
    {
        return mysql_num_rows($result);
    }

    function get_error()
    {
        return mysql_errno($this->db_link) . ': ' . mysql_error($this->db_link);
    }

    function connect()
    {
        if (!$this->db_link = mysql_connect($this->db_host, $this->db_user, $this->db_password)) {
            $this->report_error('dbWrapper->connect()', 'Database Connection Failed');
        } else {
            if (!mysql_select_db($this->database))
                $this->report_error('dbWrapper->connect()', 'Database Selection Failed');
        }
        return true;
    }

    function report_error($location, $message, $query = '')
    {
    	if(!defined('DEBUG')) 
		$query = 'Enable debug mode to view the query';
	$txt = "
<html>
<head>
<title>Database Error</title>
<style type=\"text/css\">
body {
	font-family: arial;
	font-size: 13;
}
</style>
</head>
<body>
<center>
<h1>Database Error</h1>
<p>dbWrapper generated error report:</p>
<textarea rows=\"10\" cols=\"40\">
The error occurred in:
{$location}
The function returned:
{$message}
MySQL returned:
{$this->get_error()}
MySQL query was:
{$query}
</textarea>
</center>
</body>
</html>
		";
        die($txt);
    }
}

?>
